#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("文件");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    myfile = QFileDialog::getOpenFileName(this, "我的文件对话框", "C:/test", "*.txt *.png");
    file = new QFile(myfile, this);
    ui->textBrowser->setText("已选择文件:" + myfile);
}

void MainWindow::on_pushButton_2_clicked()
{
    if (myfile.isEmpty())
    {
        ui->textBrowser->setText("请先选择文件");
        return;
    }
    if (!file->isOpen())
        file->open(QIODevice::ReadOnly);
    auto info = file->readAll();
    ui->textBrowser->setText(info);
    file->seek(0);
}

void MainWindow::on_pushButton_3_clicked()
{
    if (file->exists())
        file->close();
    file->open(QIODevice::WriteOnly);
    file->write(ui->textEdit->toPlainText().toUtf8());
    file->close();
    qDebug() << "写入成功!";
}

void MainWindow::on_pushButton_4_clicked()
{
    if (myfile.isEmpty())
    {
        ui->textBrowser->setText("请先选择文件");
        return;
    }
    if (!file->isOpen())
        file->open(QIODevice::ReadOnly);
    auto info = file->readLine();
    ui->textBrowser->setText(info);
}

void MainWindow::on_pushButton_5_clicked()
{
    if (myfile.isEmpty())
    {
        ui->textBrowser->setText("请先选择文件");
        return;
    }
    if (!file->isOpen())
        file->open(QIODevice::ReadOnly);
    auto info = file->read(1);
    ui->textBrowser->setText(info);
}

void MainWindow::on_pushButton_6_clicked()
{
    if(myfile.length() == 0)
        return;
    if(!file->isOpen())
        file->open(QIODevice::ReadOnly);
    QFileInfo fileInfo(*file);
    QString fileName = fileInfo.path()+ "/" +fileInfo.baseName()+"_copy." + fileInfo.suffix();
    ui->textBrowser->setText("正在复制文件:" + myfile);
    QFile file1(fileName);
    file1.open(QIODevice::WriteOnly | QIODevice::Append);
    while (!file->atEnd())
    {
        QString buff = file->readLine();
        file1.write(buff.toUtf8());
    }

    ui->textBrowser->setText(ui->textBrowser->toPlainText() + "\n复制完成 文件名为:" + fileName);

    file->close();
    file1.close();

}
